/**
 * Copyright (C) 2011 Audit Logger Project. All rights reserved.
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.auditlogger.security;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;

import org.auditlogger.config.ConfigurationServices;
import org.auditlogger.config.spi.PropertiesConfigurator;
import org.auditlogger.config.util.ConfigurationException;
import org.auditlogger.util.Base64EncoderDecoder;

class SignatureVerifier {
	
	private static PropertiesConfigurator config = ConfigurationServices.getPropertiesConfigurator();
	
	static boolean verify (String base64EncodedSignature, String data) 
	        throws EncryptionException, ConfigurationException {
	    try {
		return verify (Base64EncoderDecoder.decodeFromBase64(base64EncodedSignature), 
				data.getBytes(config.defaultEncoding()));
	    } catch (UnsupportedEncodingException e) {
	    	throw new EncryptionException(e.getMessage(), e);
        } catch (IOException e) {
        	throw new EncryptionException(e.getMessage(), e);
	    }
	}
	
	static boolean verify(byte[] signature, byte[] data) throws ConfigurationException, EncryptionException {
		Signature signer;
		try {
			signer = Signature.getInstance(config.getSignatureAlgorithm());
			PublicKey publicKey = config.getSignerPublicKey();
			signer.initVerify(publicKey);
			signer.update(data);
			return signer.verify(signature);
		} catch (NoSuchAlgorithmException e) {
			throw new ConfigurationException(e.getMessage(), e);
		} catch (SignatureException e) {
			throw new EncryptionException(e.getMessage(), e);
		} catch (InvalidKeyException e) {
			throw new ConfigurationException(e.getMessage(), e);
		}
	}
}
